import { getLoanStatus } from '@/api/flow/work';
import { getBankAuthStatus, getBankAuthURL } from '@/api/risk/auth';
import { START_ACTION } from '@/utils/actions';

export default {
  data() {
    return {
      loading: false,

      loanModal: {
        title: '银行授权',
        visible: false,
        url: ''
      }
    };
  },

  computed: {
    loanDisabled() {
      return (this.risk.amount <= 0)
        || !this.authentication;
    }
  },

  methods: {
    // 打开弹窗
    openwindow(url, name, iWidth, iHeight) {
      this.loanModal.url = url;

      // this.$nextTick(() => {
      //   this.loanModal.visible = true;
      // });
      const iTop = (window.screen.height-30-iHeight)/2;       //获得窗口的垂直位置;
      const iLeft = (window.screen.width-10-iWidth)/2;        //获得窗口的水平位置;
      const option = `height: ${iHeight}, innerHeight=${iHeight},
          width=${iWidth}, innerWidth=${iWidth}, 
          top=${iTop}, left=${iLeft},
          toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no`
      const newWin = window.open(
        url,
        'null',
        option
      );
      // newWin.document.write('<body scroll="no" style="margin: 0px;padding: 0px;border:0px;overflow:hidden;"><iframe style="margin: 0px;padding: 0px;border: 0px;width:100%;height:100%" src="https://dazi.91xjr.com/typing/train/letter.html"></iframe></body>');

      // newWin.document.write(`<body scroll="no" style="margin: 0px;padding: 0px;border:0px;overflow:hidden;"><iframe style="margin: 0px;padding: 0px;border: 0px;width:100%;height:100%" src="${url}"></iframe></body>`);

    //   var browser = navigator.appName;
    //   if（browser ==" Microsoft Internet Explorer"）
    //     {
    //     window.opener = self;

    //   }
    //   window.open（'filename.htm'，'null'，'width = 900，height = 750，
    //  工具栏= no，scrollbars = no，location =否，可调整大小=是'）；
    //   window.moveTo（0,0）;
    //   window.resizeTo（screen.width，screen.height-100）;
    //   self.close（）;
    },

    // submitLoan
    async submitLoan() {
      // 用户认证检查
      const isAuth = this.userAuthCheck();
      if (isAuth) return false;

      this.loading = true;

      try {
        // 银行授权判断
        const res = await this.bankAuthCheck();
        if (res) {
          const data = await this.getBankAuthURL();
          this.openwindow(data.auth_url, '授权', 1100, 800);
          this.loading = false;
          // window.open(data.auth_url, 'newwindow', 'height=800, width=1100, top=center,left=center, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no')
          return false;
        }

        await this.getLoanStatus();

        await this.submitAction(START_ACTION, this.actionData(this.formFields));
        this.$notification.success({
          message: 'Loan succeeded!',
          duration: 1
        });

        this.loading = false;

        this.$emit('loan');
          // try {
          //   await this.getTemplateFields();

          //   await this.submitAction(AGREE_ACTION, this.actionData(this.loanFormFields))

          // } catch (error) {
          //   this.formLoading = false;
          //   this.$notification.error({ message: 'Loan failed, please try again!' });
          // }
      } catch (err) {
        this.loading = false;
      }
    },

    // authentication rule
    userAuthCheck() {
      if (!this.authentication) {
        const modalProps = {
          okButtonProps: {
            props: {
              shape: 'round'
            }
          },
          cancelButtonProps: {
            props: {
              shape: 'round'
            }
          }
        };

        const _self = this;

        this.$confirm({
          title: 'Tips',
          content: 'You need to complete your personal information and bank account information to get your loan limit!',
          cancelText: 'Cancel',
          okText: 'To perfect',
          ...modalProps,
          onOk() {
            _self.$router.push({
              name: 'ModifyBasicSettings'
            });
          }
        });

        return true;

        throw new Error();
      }
    },

    // 银行授权
    bankAuthCheck() {
      return new Promise((resolve, reject) => {
        getBankAuthStatus()
          .then((data) => {
            resolve(data.status === 0);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 银行授权地址
    getBankAuthURL() {
      return new Promise((resolve, reject) => {
        getBankAuthURL()
          .then((data) => {
            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // loan status
    async getLoanStatus() {
      try {
        const data = await getLoanStatus();

        return data;
      } catch (error) {
        throw Error(error);
      }
    }
  }
};
